import researchMemberList from '@views/gfxy/common/researchMemberList'
import { getAction, httpAction } from '@api/manage'

export const GfxyResearchMemberListMixin = {
  components: {
    researchMemberList
  },
  data() {
    return {
      title: '操作',
      visible: false,
      confirmLoading: false,
      memberListTable: {
        loading: false,
        dataSource: [],
      },
      url:{
        list: '/research/researchCommon/queryMemberListByMainId'
      },
      model:{
        projectType: this.projectType,
        totalScore: 0.0,
        date: this.date
      },
    }
  },
  methods: {
    add(){
      console.log(this.model)
      this.edit(this.model)
    },

    edit(record){
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)


      this.$nextTick(() => {
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(params)
        }
      })

      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },

    requestSubTableData(params,success) {
      let _that = this;
      this.memberListTable.loading = true
      getAction(_that.url.list, params).then(res => {
        let { result } = res
        let dataSource = []
        if (result) {
          if (Array.isArray(result)) {
            dataSource = result
          } else if (Array.isArray(result.records)) {
            dataSource = result.records
          }
        }
        console.log(dataSource)
        _that.memberListTable.dataSource = dataSource
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        _that.memberListTable.loading = false
      })
    },
    classifyIntoFormData(allValues) {
      // let main = Object.assign(this.model, allValues.formValue)
      return {
        ...this.model, // 展开
        memberListList: this.memberListTable.dataSource,
      }
    },


    validateError(msg){
      this.$message.error(msg)
    },

    request(formData) {
      let url = this.url.add, method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    close() {
      this.visible = false
      this.$emit('close')
    },
    handleCancel() {
      this.close()
    },
    updateMemberList(){
      this.$nextTick(() => {
        this.$refs.memberListRef.computeScore()
      })
    },
    handleOk(){
      new Promise((resolve, reject) => {
        // 验证主表表单
        console.log("开始校验主表信息")
        this.$refs.form.validate((valid,obj) => {
          valid ? resolve() : reject(obj)
        })
      }).then(()=>{
        console.log("主表信息校验成功，开始校验成员列表")
        return new Promise((resolve, reject) => {
          this.$refs.memberListRef.validateList() ? resolve(): reject('请检查成员列表')
        }).then(() => {

          return new Promise((resolve, reject) => {
              if(this.memberListTable.dataSource.length > 0){
                resolve()
              } else {
                reject("请添加成员")
              }
          }).then(() => {
            console.log("成员列表校验成功， 开始校验工作量分配")
            return new Promise((resolve,reject) => {
              let result = 0;

              this.memberListTable.dataSource.forEach(item =>{
                result = result + item.score
              })
              result = this.$math.round(result);
              console.log(result,this.model.totalScore)

              if(result > this.model.totalScore){
                reject("积分总和超过总积分")
              } else {
                resolve();
              }

            }).then(() =>{
              console.log("准备提交数据")
              // this.memberListTable.dataSource.forEach(item =>{
              //   item.matchType = this.memberListTable.matchType;
              // })
              let formData = this.classifyIntoFormData()
              console.log("发送数据",formData)
              // 发起请求
              console.log(formData)
              return this.request(formData)
            }).catch((msg)=>{
              console.log("成员列表校验失败： " + msg)
              this.validateError(msg)
              return false;
            })
          }).catch((msg)=>{
            console.log("成员个数校验失败： " + msg)
            this.validateError(msg)
            return false;
          })


        }).catch((msg)=>{
          console.log("成员列表校验失败： " + msg)
          this.validateError(msg)
          return false;
        })
      }).catch((obj)=>{
        console.log("主表校验失败")
        this.validateError('请输入必填项')
        return false;
      })
    }
  }
}